package lumis.portal.deployment;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import lumis.portal.PortalConfiguration;
import lumis.portal.filesystem.PortalBaseFolder;
import lumis.util.security.Base64;

/**
 * Utility class for the deployment package.
 *
 * @version $Revision: 13093 $ $Date: 2011-05-28 18:40:18 -0300 (Sat, 28 May 2011) $
 * @since 6.0.0
 */
class DeploymentUtil
{
	/**
	 * Utility method to obtain an archive file relative to a module.
	 * @param moduleId the module identifier.
	 * @param moduleType the module type.
	 * @return the file.
	 * @since 6.0.0
	 */
	public static File getArchiveFile(String moduleId, ModuleType moduleType)
	{
		switch(moduleType)
		{
			case JAR_LIBRARY:
				return new File(PortalBaseFolder.DATA.getAbsolutePath("installedmodules/lib/" + moduleId));
			default:
				throw new IllegalArgumentException("Unknown module type: " + moduleType);
		}
	}

	/**
	 * Utility method to obtain the reference to the auto-deploy file for a 
	 * module.
	 * @param moduleId the module identifier.
	 * @return the file.
	 * @since 6.0.0
	 */
	public static File getAutoDeployFile(String moduleId)
	{
		return new File(PortalConfiguration.getCurrentConfiguration().getLumisDataPath() + "/deploy/" + moduleId);
	}

	/**
	 * Calculates a checksum for the given file, to be used to verify
	 * if the file content if different.
	 * @param file the file.
	 * @return the checksum.
	 * @throws IOException if an error occurred while reading the file.
	 * @since 6.0.0
	 */
	public static String calculateChecksum(File file) throws IOException
	{
		// get SHA-1 digest
	    MessageDigest messageDigest;
		try
		{
			messageDigest = MessageDigest.getInstance("SHA-1");
		}
		catch (NoSuchAlgorithmException e)
		{
			throw new RuntimeException(e);
		}
	    
		// calculate digest
		InputStream is = new FileInputStream(file);
		try
		{
			int bytesRead;
			byte[] readBuffer = new byte[2048];
			while((bytesRead = is.read(readBuffer)) != -1) 
				messageDigest.update(readBuffer, 0, bytesRead);
			
		}
		finally
		{
			is.close();
		}
		
		// return digest encoded in base64
	    return Base64.encode(messageDigest.digest());
	}
}
